package cn.vivi.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.vivi.domain.vo.ClassesVo;
import cn.vivi.mapper.ProductMapper;
import cn.vivi.service.ClassesService;
import cn.vivi.service.impl.ClassesServiceImpl;
import cn.vivi.util.JsonUtils;
import cn.vivi.util.Result;

@WebServlet("/homes")
@SuppressWarnings("all")
public class HomeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private ClassesService classesService = new ClassesServiceImpl();
	private ProductMapper productMapper = new ProductMapper();

	private void initParamer(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		initParamer(request, response);
		response.setContentType("application/json;charset=utf8");
		List<ClassesVo> vos = new ArrayList<ClassesVo>(30);
		classesService.findAll().forEach(c -> {
			try {
				int count = productMapper.count(c.getId() + "");
				ClassesVo vo = new ClassesVo();
				vo.setCount(count);
				vo.setClassesName(c.getName());
				vos.add(vo);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		});
		JsonUtils.toJson(response, Result.success().setData("vos", vos));
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
